package com.android.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.functions.GetSetJSON;
import com.android.functions.VariaveisGlobais;
import com.android.projetoavista1.R;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;

public class ListaDeLojasActivity extends ListActivity {
	public ListView lista;
	public int contador=0;

	private ArrayList<HashMap<String, String>> mLojasList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_lojas_aoredor);
		
		Spinner spnUf = (Spinner)findViewById(R.id.spnUf);
		Spinner spnCidade = (Spinner)findViewById(R.id.spnCidade);
		Spinner spnBairro = (Spinner)findViewById(R.id.spnBairro);
		final Button btnBuscar = (Button)findViewById(R.id.btnBuscaLoja);
		
		spnCidade.setEnabled(false);
		spnBairro.setEnabled(false);
		btnBuscar.setEnabled(false);
		
		new ConsultaEstado().execute();
		
		spnUf.setOnItemSelectedListener(new OnItemSelectedListener() {
		    @Override
		    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
		    	contador++;
		    	Log.i("Contador",contador+"");
		    	new ConsultaCidade().execute();
		    }

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				//Metodo Obrigatorio mas sem uso;
			}
		});
		
		spnCidade.setOnItemSelectedListener(new OnItemSelectedListener() {
		    @Override
		    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
	    		contador++;
	    		Log.i("Contador",contador+"");
		    	new ConsultaBairro().execute();
		    }

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				//Metodo Obrigatorio mas sem uso;
			}
		});
		
		spnBairro.setOnItemSelectedListener(new OnItemSelectedListener() {
		    @Override
		    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
	    		contador++;
	    		Log.i("Contador",contador+"");
		    	if (contador==9){
	    			btnBuscar.setEnabled(true);
	    		}
		    }

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				//Metodo Obrigatorio mas sem uso;
			}
		});
		
		getListView().setOnItemClickListener(new OnItemClickListener() { 
	 		 public void onItemClick(AdapterView<?> arg0, View arg1, int pst, long id) {
	 			HashMap<String, String> lojaSelecionada = new HashMap<String, String>();	
	 			lojaSelecionada=mLojasList.get(pst);
	 			VariaveisGlobais.lojaCodigo=lojaSelecionada.get("CODIGO");
	 			VariaveisGlobais.lojaNome=lojaSelecionada.get("NOME");
	 			VariaveisGlobais.lojaTelefone=lojaSelecionada.get("TELEFONE");
	 			VariaveisGlobais.lojaEndereco=lojaSelecionada.get("ENDERECO");
	 			VariaveisGlobais.lojaTipoCartao=lojaSelecionada.get("TIPO_CARTAO");
                Intent it = new Intent(ListaDeLojasActivity.this,DetalhaLoja.class);//Preparando a nova activity;
                startActivity(it);//Inciando a nova Activity;
                ListaDeLojasActivity.this.finish();
		 	} 
	 	});
	}

	
	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(ListaDeLojasActivity.this)
		.setTitle("Deseja Cancelar?")
		.setMessage(
				"Ao cancelar o processo este nï¿½mero de celular nï¿½o poderï¿½ ser ultilizado em uma nova proposta.")
		.setNegativeButton("Nï¿½o", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).setPositiveButton("Sim", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		}).show();	
	}
	
	
	public void detalhaLoja(View v) {
		new ConsultaLojas().execute();
	}

	public class ConsultaEstado extends AsyncTask<Void,Void,Void>{
		
		String openUrl="http://177.125.181.172/BossRest/nao/cliente/consultar/uf/";
		JSONObject jsonResposta1 = new JSONObject();
		JSONArray jsonResposta2 = new JSONArray();
		JSONObject jsonEnvio = new JSONObject();
		GetSetJSON getSetJson = new GetSetJSON();
		public ProgressDialog pDialog;
		int jsonRetorno=1;
		String jsonMensagem;
		boolean semConexao=true;
		List<String> jsonUf = new ArrayList<String>();
		public ArrayAdapter<String> adapter;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ListaDeLojasActivity.this);
			pDialog.setMessage("Aguarde um instante...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			try {
				semConexao=false;
				jsonEnvio.put("", "");
				jsonResposta1 = getSetJson.enviarSolicitacao(openUrl, jsonEnvio);
				jsonRetorno = jsonResposta1.getInt("RETORNO");
				if (jsonRetorno==0){
					jsonResposta2 = jsonResposta1.getJSONArray("DADOS");
					jsonUf.add("SELECIONE");
					for (int cont = 0; cont != jsonResposta2.length(); cont++) {
						JSONArray jsonResposta3 = jsonResposta2.getJSONArray(cont);
						for (int cont1 = 0; cont1 != jsonResposta3.length(); cont1++) {
							if (cont1 == 1) {
								jsonUf.add(jsonResposta3.getString(cont1));
							}
						}
					}
				}else{
					jsonMensagem=jsonResposta1.getString("MENSAGEM");
				}
			} catch (JSONException e) {
				Log.i("JSONException", e.getMessage());
				jsonRetorno=1;
			} catch (ClientProtocolException e) {
				Log.i("ClientProtocolException", e.getMessage());
				jsonRetorno=1;
			} catch (IOException e) {
				Log.i("IOException", e.getMessage());
				semConexao=true;
				jsonRetorno=1;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void Void) {
			pDialog.dismiss();
			if (jsonRetorno == 0) {
				Spinner spnUf = (Spinner) findViewById(R.id.spnUf);
				adapter = new ArrayAdapter<String>(ListaDeLojasActivity.this,android.R.layout.simple_spinner_item, jsonUf);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
				spnUf.setAdapter(adapter);
			} else {
				if (semConexao == false) {
					new AlertDialog.Builder(ListaDeLojasActivity.this)
							.setTitle("Atenï¿½ï¿½o")
							.setMessage(jsonMensagem.toString())
							.setNeutralButton("ok", null).show();
				} else {
					new AlertDialog.Builder(ListaDeLojasActivity.this)
					.setTitle("AtenÃ§Ã£o")
					.setMessage(
							"Sem conexÃ£o de rede.")
					.setPositiveButton("OK", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(ListaDeLojasActivity.this,PropostaAprovada.class);
							startActivity(intent);
							ListaDeLojasActivity.this.finish();
							dialog.dismiss();
						}
					}).show();
				}
			}
		}
	}

	
	public class ConsultaCidade extends AsyncTask<Void,Void,Void>{
		String openUrl="http://177.125.181.172/BossRest/nao/cliente/consultar/cidade/";
		JSONObject jsonResposta1 = new JSONObject();
		JSONArray jsonResposta2 = new JSONArray();
		JSONObject jsonEnvio = new JSONObject();
		GetSetJSON getSetJson = new GetSetJSON();
		int jsonRetorno=1;
		String jsonMensagem;
		boolean semConexao=true;
		List<String> jsonCidade = new ArrayList<String>();
		public ArrayAdapter<String> adapter;
		
		protected Void doInBackground(Void... params) {
			try {
				semConexao=false;	
				final Spinner spnUf = (Spinner)findViewById(R.id.spnUf);
				jsonEnvio.put("PARAM_UF", spnUf.getSelectedItem().toString());
				Log.i("Log Json", jsonEnvio.toString());
				jsonResposta1 = getSetJson.enviarSolicitacao(openUrl, jsonEnvio);
				jsonRetorno = jsonResposta1.getInt("RETORNO");
				if (jsonRetorno==0){
					jsonResposta2 = jsonResposta1.getJSONArray("DADOS");
					jsonCidade.add("SELECIONE");
					for (int cont = 0; cont != jsonResposta2.length(); cont++) {
						JSONArray jsonResposta3 = jsonResposta2.getJSONArray(cont);
						for (int cont1 = 0; cont1 != jsonResposta3.length(); cont1++) {
							if (cont1 == 1) {
								jsonCidade.add(jsonResposta3.getString(cont1));
							}
						}
					}
				}else{
					jsonMensagem=jsonResposta1.getString("MENSAGEM");
				}
			} catch (JSONException e) {
				Log.i("JSONException", e.getMessage());
				jsonRetorno=1;
			} catch (ClientProtocolException e) {
				Log.i("ClientProtocolException", e.getMessage());
				jsonRetorno=1;
			} catch (IOException e) {
				Log.i("IOException", e.getMessage());
				semConexao=true;
				jsonRetorno=1;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void Void) {
			if (jsonRetorno == 0) {
				Spinner spnCidade = (Spinner) findViewById(R.id.spnCidade);
				adapter = new ArrayAdapter<String>(ListaDeLojasActivity.this,android.R.layout.simple_spinner_item, jsonCidade);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
				if (contador==4){
					spnCidade.setEnabled(true);
				}
				spnCidade.setAdapter(adapter);
			} else {
				if (semConexao == false) {
					new AlertDialog.Builder(ListaDeLojasActivity.this)
							.setTitle("Atenï¿½ï¿½o")
							.setMessage(jsonMensagem.toString())
							.setNeutralButton("ok", null).show();
				} else {
					new AlertDialog.Builder(ListaDeLojasActivity.this)
					.setTitle("AtenÃ§Ã£o")
					.setMessage(
							"Sem conexÃ£o de rede.")
					.setPositiveButton("OK", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(ListaDeLojasActivity.this,PropostaAprovada.class);
							startActivity(intent);
							ListaDeLojasActivity.this.finish();
							dialog.dismiss();
						}
					}).show();
				}
			}
		}
	}
	
	public class ConsultaBairro extends AsyncTask<String,Void,Void>{
		String openUrl="http://177.125.181.172/BossRest/nao/cliente/consultar/bairro/";
		JSONObject jsonResposta1 = new JSONObject();
		JSONArray jsonResposta2 = new JSONArray();
		JSONObject jsonEnvio = new JSONObject();
		GetSetJSON getSetJson = new GetSetJSON();
		int jsonRetorno=1;
		String jsonMensagem;
		boolean semConexao=true;
		List<String> jsonBairro = new ArrayList<String>();
		public ArrayAdapter<String> adapter;
		
		protected Void doInBackground(String... params) {
			try {
				semConexao=false;
				final Spinner spnUf = (Spinner)findViewById(R.id.spnUf);
				final Spinner spnCidade = (Spinner)findViewById(R.id.spnCidade);
				jsonEnvio.put("PARAM_UF", spnUf.getSelectedItem().toString());
				jsonEnvio.put("PARAM_CIDADE", spnCidade.getSelectedItem().toString());
				Log.i("Log Json", jsonEnvio.toString());
				jsonResposta1 = getSetJson.enviarSolicitacao(openUrl, jsonEnvio);
				jsonRetorno = jsonResposta1.getInt("RETORNO");
				if (jsonRetorno==0){
					jsonResposta2 = jsonResposta1.getJSONArray("DADOS");
					jsonBairro.add("SELECIONE");
					for (int cont = 0; cont != jsonResposta2.length(); cont++) {
						JSONArray jsonResposta3 = jsonResposta2.getJSONArray(cont);
						for (int cont1 = 0; cont1 != jsonResposta3.length(); cont1++) {
							if (cont1 == 1) {
								jsonBairro.add(jsonResposta3.getString(cont1));
							}
						}
					}
				}else{
					jsonMensagem=jsonResposta1.getString("MENSAGEM");
				}
			} catch (JSONException e) {
				Log.i("JSONException", e.getMessage());
				jsonRetorno=1;
			} catch (ClientProtocolException e) {
				Log.i("ClientProtocolException", e.getMessage());
				jsonRetorno=1;
			} catch (IOException e) {
				Log.i("IOException", e.getMessage());
				semConexao=true;
				jsonRetorno=1;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void Void) {
			if (jsonRetorno == 0) {
				Spinner spnBairro = (Spinner) findViewById(R.id.spnBairro);
				adapter = new ArrayAdapter<String>(ListaDeLojasActivity.this,android.R.layout.simple_spinner_item, jsonBairro);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
				if (contador==7){
					spnBairro.setEnabled(true);
				}
				spnBairro.setAdapter(adapter);
			} else {
				if (semConexao == false) {
					new AlertDialog.Builder(ListaDeLojasActivity.this)
							.setTitle("Atenï¿½ï¿½o")
							.setMessage(jsonMensagem.toString())
							.setNeutralButton("ok", null).show();
				} else {
					new AlertDialog.Builder(ListaDeLojasActivity.this)
					.setTitle("AtenÃ§Ã£o")
					.setMessage(
							"Sem conexÃ£o de rede.")
					.setPositiveButton("OK", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(ListaDeLojasActivity.this,PropostaAprovada.class);
							startActivity(intent);
							ListaDeLojasActivity.this.finish();
							dialog.dismiss();
						}
					}).show();
				}
			}
		}
	}
	
	public class ConsultaLojas extends AsyncTask<Void, Void, Void> {
		public GetSetJSON getSetJson = new GetSetJSON();
		public ProgressDialog pDialog;
		public String openURL = "http://177.125.181.172/BossRest/nao/cliente/consultar/lojas/";
		JSONObject jsonEnvio = new JSONObject();
		JSONObject jsonResposta1 = new JSONObject();
		boolean semConexao = true;
		public int jsonRetorno = 1;
		public String jsonMesagem;
		JSONArray jsonResposta2 = new JSONArray();

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ListaDeLojasActivity.this);
			pDialog.setMessage("Aguarde um instante...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			mLojasList = new ArrayList<HashMap<String, String>>();
			GetSetJSON getSetJson = new GetSetJSON();
			try {
				final Spinner spnUf = (Spinner)findViewById(R.id.spnUf);
				final Spinner spnCidade = (Spinner)findViewById(R.id.spnCidade);
				final Spinner spnBairro = (Spinner)findViewById(R.id.spnBairro);
				jsonEnvio.put("PARAM_UF",spnUf.getSelectedItem().toString());
				jsonEnvio.put("PARAM_CIDADE",spnCidade.getSelectedItem().toString());
				jsonEnvio.put("PARAM_BAIRRO", spnBairro.getSelectedItem().toString());
				Log.i("JSON", jsonEnvio.toString());
				JSONObject jsonResposta1 = getSetJson.enviarSolicitacao(openURL,jsonEnvio);
				jsonRetorno=jsonResposta1.getInt("RETORNO");
				if (jsonRetorno==0){
			 		jsonResposta2 = jsonResposta1.getJSONArray("DADOS");
			 		for(int cont=0;cont!=jsonResposta2.length();cont++){ 
			 			JSONObject jsonResposta3 = jsonResposta2.getJSONObject(cont); 
			 			HashMap<String, String> map = new HashMap<String, String>();
			 			map.put("CODIGO", jsonResposta3.getString("CODIGO"));
			 			map.put("NOME", jsonResposta3.getString("NOME"));
			 			map.put("ENDERECO", jsonResposta3.getString("ENDERECO"));
			 			map.put("TELEFONE", jsonResposta3.getString("TELEFONE"));
			 			map.put("TIPO_CARTAO", jsonResposta3.getString("TIPO_CARTAO"));
			 			mLojasList.add(map);
			 		} 
			 	}else{
		 			jsonMesagem=jsonResposta1.getString("MENSAGEM"); 
	 			} 
			} catch(JSONException e) { 
				Log.i("Log1", e.getMessage()); 
				jsonRetorno=1; 
			}catch (ClientProtocolException e) { 
				Log.i("Log2", e.getMessage());
			 	jsonRetorno=1; 
		 	} catch (IOException e) { 
		 		Log.i("Log3",e.getMessage()); 
		 		jsonRetorno=1; 
		 		semConexao=true;
			}
			return null;
		}


		@Override
		protected void onPostExecute(Void Void) {
			pDialog.dismiss();
			if (jsonRetorno==0){
				if(jsonResposta2.length()==0){
					new AlertDialog.Builder(ListaDeLojasActivity.this)
					.setTitle("AtenÃ§Ã£o")
					.setMessage("Nenhuma loja foi encontrada.")
					.setNeutralButton("OK", null).show();
					setListAdapter(null);
				}else{
					ListAdapter adapter = new SimpleAdapter
							(	ListaDeLojasActivity.this,
								mLojasList, 
								R.layout.item_lista_lojas, new String[] {"NOME","ENDERECO"}, 
								new int[] {R.id.txtNomeLoja, R.id.txtEndLoja }
							);
					setListAdapter(adapter);
				}
			}else{
				if(semConexao!=true){
					new AlertDialog.Builder(ListaDeLojasActivity.this).setTitle("Atenï¿½ï¿½o").setMessage(jsonMesagem)
					.setPositiveButton("OK", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(ListaDeLojasActivity.this,PropostaAprovada.class);
							startActivity(intent);
							ListaDeLojasActivity.this.finish();
						}
					}).show();
				}else{
					new AlertDialog.Builder(ListaDeLojasActivity.this)
					.setTitle("AtenÃ§Ã£o")
					.setMessage("Sem conexÃ£o de rede.")
					.setNeutralButton("OK", null).show();
				}
			}
		}
	}
}
